# -*- encoding:utf8 -*-
from django.utils import timezone
from attendance.convert import date2str
from staff.models import StaffInfo
from attendance.models import LeaveApplication,AvaiLeave
from leave_info import dictfy
from attendance.tool_func import get_or_none

def filter_leave_app(start_date=None,end_date=None,keyword=None):
    """
    根据过滤条件，查询LeaveApplication
    """
    dc={}

    # if not start_date or not end_date:
        # now=timezone.now().date()
        # firstday=date2str(now.replace(day=1))
        # nowstr=date2str(now)       
        # start_date=firstday
        # end_date=nowstr
    start_date,end_date=_process_date(start_date, end_date)
    dc['start_time__gte']=start_date+' 06:00'
    dc['start_time__lte']=end_date+' 23:00'
    if keyword:
        if keyword.startswith('AE'):
            staff=get_or_none(StaffInfo,employee_id=keyword)
            if staff:
                dc['staff']=staff
        else:
            sl=[]
            for staff in StaffInfo.objects.filter(cn_name__icontains=keyword)|StaffInfo.objects.filter(en_name__icontains=keyword):
                sl.append(staff)
            dc['staff__in']=sl
            
    out=[]

    for row in LeaveApplication.objects.filter(**dc):
        out.append(dictfy(row))
    return out

def filter_avai_leave(start_date=None,end_date=None,category=None,keyword=None,only_valid=None):
    """
    过滤 avai
    """
    dc={}
    start_date,end_date=_process_date(start_date, end_date)
    # if start_date and end_date:
    dc['start_date__gte']=start_date
    dc['start_date__lte']=end_date    
    if only_valid:
        dc['is_valid']=True
    if keyword:
        _keyword_2_staffs(keyword, dc)
    out=[]
    for row in AvaiLeave.objects.filter(**dc):
        out.append(dictfy(row))
    return out


def _process_date(start_date,end_date):
    """
    如果start_date,end_date不完整，就返回当月的firstday,now 两个日期
    """
    if not start_date or not end_date:
        now=timezone.now().date()
        firstday=date2str(now.replace(day=1))
        nowstr=date2str(now)       
        start_date=firstday
        end_date=nowstr 
    return start_date,end_date

    
def _keyword_2_staffs(keyword,dc):
    if keyword.startswith('AE'):
        staff=get_or_none(StaffInfo,employee_id=keyword)
        if staff:
            dc['staff']=staff
    else:
        sl=[]
        for staff in StaffInfo.objects.filter(cn_name__icontains=keyword)|StaffInfo.objects.filter(en_name__icontains=keyword):
            sl.append(staff)
        dc['staff__in']=sl    